package com.qc.common;

import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DBUtil {
	private static Logger logger = Logger.getLogger(DBUtil.class);
	private static Map<String, String> _sqlCache;
	static {
		_sqlCache = new HashMap<String, String>();
		DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); 
		DocumentBuilder builder;
		try {
			builder = factory.newDocumentBuilder();
			Document doc = builder.parse(DBUtil.class.getClassLoader().getResourceAsStream(Constants.SQL_FILE_NAME)); 
			NodeList sqls = doc.getElementsByTagName(Constants.SQL_TAG);
			for (int i = 0; i < sqls.getLength(); i++) {
				Node node = sqls.item(i);
				NamedNodeMap attr = node.getAttributes();
				String id = attr.getNamedItem(Constants.SQL_ID).getNodeValue().trim();
				String sql = node.getFirstChild().getNodeValue().trim();
				
				_sqlCache.put(id, sql);
				
				if (sql == null || "".equals(sql.trim())) {
					logger.error("sql.xml is wrong!![%s]" + id);
				}
			}
		} catch (Exception e) {
			logger.error(e.getStackTrace().toString());
		} 
	}
	
	/**
	 * getSql:得到配置的sql
	 *
	 * @param  @param id
	 * @param  @return
	 * @return String
	 * @throws 
	*/
	public static String getSql(String id) {
		String sql = _sqlCache.get(id);
		return sql;
	}
}
